package io.gitee.hchaojie.day03.tetris;

import javafx.scene.Group;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class Brick extends Group implements Cloneable {
	private static final Lighting DEFAULT_EFFECT = new Lighting(
			new Light.Spot(0, 0, 100, 0, Color.WHITE));

	// 实例变量（成员变量）
    private int[][] matrix;
    private double squareSize;
    private Color color;

	public Brick(int[][] matrix, Color color, double size) {
		this.matrix = matrix;
		this.setSquareSize(size);
		this.color = color;

		// 局部变量
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				Rectangle rectangle = new Rectangle();
				rectangle.setWidth(getSquareSize());
				rectangle.setHeight(getSquareSize());

				if (matrix[i][j] == 1) {
					rectangle.setFill(this.color);
					rectangle.setArcHeight(8);
					rectangle.setArcWidth(8);
					rectangle.setEffect(DEFAULT_EFFECT);
				} else {
					// 需要为空的地方创建一个透明的小方块
					// 否则会影响砖块的translateX，translateY计算
					rectangle.setOpacity(0);
				}

				rectangle.setTranslateY(getSquareSize() * i);
				rectangle.setTranslateX(getSquareSize() * j);
				
				getChildren().add(rectangle);
			}
		}
	}
	
	public int[][] getMatrix() {
		return matrix;
	}

	public void setMatrix(int[][] matrix) {
		this.matrix = matrix;
	}
	
	/** 
	 * 砖块旋转，需要将矩阵倒置
	 */
	public int[][] rotate() {
		int[][] m = this.matrix;
		int[][] result = new int[m.length][m.length];

		for (int i = 0; i < m.length; i++) {
			int len = m[i].length;
			for (int j = 0; j < len; j++) {
				result[i][j] = m[len - j - 1][i];
			}
		}
		
		return result;
	}

	public Rectangle createRectangle() {
		Rectangle rectangle = new Rectangle();
		rectangle.setWidth(getSquareSize());
		rectangle.setHeight(getSquareSize());

		rectangle.setFill(this.color);
		rectangle.setArcHeight(8);
		rectangle.setArcWidth(8);
		rectangle.setEffect(DEFAULT_EFFECT);;
		
		return rectangle;
	}

	public double getSquareSize() {
		return squareSize;
	}

	public void setSquareSize(double squareSize) {
		this.squareSize = squareSize;
	}
}